// pages/my/my.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo:{//用于保存用户数据
      nickName: '同学，请点我登录~~'
    }, 
    islogin: wx.getStorageSync("loginFlag") ? true : false // 是否登录
  },

  handleTapLogin(){
    if(this.data.islogin){
      return; //若已经登录,则直接返回,不会执行后面的语句
    }
    var that = this
    let sessionStorageId = wx.getStorageSync("sessionId")
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        wx.request({
          url: 'http://localhost:8888/user/login',
          method: 'post',
          data: {
            seesionId:sessionStorageId,
            encryptedData: res.encryptedData,
            iv: res.iv
          },
          success: function(res) {
            res = res.data
            wx.setStorageSync("token", res.data.token);
            wx.setStorageSync("loginFlag", "已登录");
            wx.request({
              url: 'http://localhost:8888/user/userinfo',
              method: 'GET',
              data: {
                token: wx.getStorageSync("token")
              },
              success:function(res){
                wx.setStorageSync("userInfo", res.data.data);
                that.setData({
                  islogin: true,//登录成功,改为true
                  userInfo: res.data.data
                })

              }
            })
          },
          fail: function (error) {
            console.log(error);
            // 获取 userInfo 失败，去检查是否未开启权限
            wx.hideLoading();
            that.showInfo("调用request接口失败");
            console.log(error);
            wx.navigateTo({
              url: "/pages/index/index",
            })
          }
        })
      }
    })
  },

  onLoad(){
    var that = this
    if(this.data.islogin){//已登录
      that.setData({
        userInfo: wx.getStorageSync('userInfo')
      })
      return 
    }
    //登录用户标识
    wx.login({
      success (res) {
        if (res.code) {
          console.log(res.code)
          //发起网络请求
          wx.request({
            url: 'http://localhost:8888/user/getSeesionId',
            method: 'POST',
            header:{
              'content-type':'application/x-www-form-urlencoded',
            },
            data: {
              code: res.code
            },
            success(res){

              if(res.data.code == 200){
                wx.setStorage({//存储到本地
                  key:'sessionId',
                  data:res.data.data
                })
              }else{
                wx.removeStorage({
                  key: 'sessionId',
                })
              }
            }
          })
        } else {
          console.log('发生错误')
        }
      }
    })
},
})